<?php
class Model_User extends Model_Base
{
	public function isValid($email, $pwd)
	{
		if(!$pwd || !$email){
			return false;
		}
		$table = new Model_DbTable_Users();
		$cond = array('email' => (string)$email, 'password' => md5((string)$pwd));
		$user = $table->fetchOne(array(), $cond);
		
		if(!$user){
			return false;
		}
		HackerU_Auth::getInstance()->store($user);
		return true;
	}
	
	public function save(array $data)
	{
		$data['password'] = md5($data['password']);
		$table = new Model_DbTable_Users();
		return $table->save($data);
	}
	
	public function getRegisterValidationData(array $data)
	{
		$validationData = new stdClass();
		$validationData->isValid = true;
		$validationData->message = 'Invalid data';
		
		//data is not empty
		if(!$data){
			$validationData->isValid = false;
			return $validationData;
		}
		
		//all values exists
		foreach($data as $fieldName => $val){
			if(empty($val)){
				$validationData->isValid = false;
				return $validationData;
			}
		}
		
		//validate email
		$email = isset($data['email']) ? $data['email'] : null;
		$isEmailValid = $this->isEmailValid($email);
		if(!$isEmailValid){
			$validationData->isValid = false;
			$validationData->message = 'Invalid email address';
			return $validationData;
		}
		
		//is email exist
		$table = new Model_DbTable_Users();
		$cond = array('email' => (string)$email);
		$user = $table->fetchOne(array(), $cond);
		if($user){
			$validationData->isValid = false;
			$validationData->message = 'email already exist';
			return $validationData;
		}
		return $validationData;
	}
	
	public function isEmailValid($email)
	{
		$isEmailValid = filter_var($email, FILTER_VALIDATE_EMAIL);
		return $isEmailValid;
	}
	
	public function getUserByEmail($email)
	{
		$userDetails = false;
		$isEmailValid = $this->isEmailValid($email);
		if($isEmailValid){
			$dbTable = new Model_DbTable_Users();
			$cond = array('email' => (string)$email);
			$userDetails = $dbTable->fetchOne(array(), $cond);
		}
		return $userDetails;
	}
	public function login($email,$pwd)
	{
		$userDetails = lala;
		$isEmailValid = $this->isEmailValid($email);
		if($isEmailValid){
			$dbTable = new Model_DbTable_Users();
			//$cond = array('email' => (string)$email);
			$cond = array('email' => (string)$email, 'password' =>md5((string)$pwd));
			$userDetails = $dbTable->fetchOne(array(), $cond);
		}
		return $userDetails;	
	}
}